package io.feige.rpc.consumer.network.handler;

import io.feige.rpc.consumer.RpcConsumerService;
import io.feige.rpc.protocol.nettyobj.pojo.IOResponseMessage;

import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class InvokerResponseHandler extends SimpleChannelHandler {

	private static Logger logger = LoggerFactory.getLogger(InvokerResponseHandler.class);
	
	private RpcConsumerService rpcConsumerService;
	
	public InvokerResponseHandler(RpcConsumerService rpcConsumerService) {
		this.rpcConsumerService=rpcConsumerService;
	}

	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
		IOResponseMessage response=(IOResponseMessage) e.getMessage();
		rpcConsumerService.getConnectionService().received(response.getResult(), response.getException(), response.getSeq());
		logger.debug("messageReceived notify request {}", e.getChannel());
		super.messageReceived(ctx, e);
	}
	
	@Override
	public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
		rpcConsumerService.getConnectionService().removeConnection(e.getChannel());
		super.channelClosed(ctx, e);
	}
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
		logger.warn("exceptionCaught", e.getCause()); 
	}
	
	@Override
	public void channelInterestChanged(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
		
		//Channel is writable, check the request queue or return to the channel pool.
		rpcConsumerService.getConnectionService().checkRequestQueue(e.getChannel());
		super.channelInterestChanged(ctx, e);
	}
	
}
